#include "QQuickROData.h"
#include "RORPC.h"
#include "RONode.h"
#include "ROHost.h"
RORPC::RORPC(QObject *parent)
{

}

void RORPC::initialize()
{
    ROSyncObject::initialize();

}

ROPlayer *RORPC::player() const
{
    return m_player;
}

void RORPC::setPlayer(ROPlayer *newPlayer)
{
    if (m_player == newPlayer)
        return;
    m_player = newPlayer;
    emit playerChanged();
}

bool RORPC::active() const
{
    return m_active;
}

void RORPC::setActive(bool newActive)
{
    if (m_active == newActive)
        return;
    m_active = newActive;
    emit activeChanged();
}



void RORPC::call(QString funName, const QVariantList& params)
{
    auto data = getROObjectData(this);
    if(!data)
    {
        return;
    }
    if(m_policy == CallOnSource)
    {
        if(role() == Host || role() == Individual)
        {
            invokeMethod(this,funName,params);
        }
        else{
            data->node->rpcCall(data->id,funName,params,m_mode == Safe);
        }
    }
    else if(m_policy == CallOnPlayer)
    {
        if(role() == Host)
        {
            if(m_player != nullptr)
            {
                data->host->broadcastRPC(data->id,funName,params,{m_player},m_mode == Safe);
            }
        }
        else{
            qDebug()<<"RPC调用失败,CallOnPlayer选项仅能在服务端使用";
        }
    }
    else if(m_policy == CallOnAllPlayers)
    {
        if(role() == Host)
        {
            data->host->broadcastRPC(data->id,funName,params,data->host->players(),m_mode == Safe);
        }
        else{
            qDebug()<<"RPC调用失败,CallOnAllPlayers选项仅能在服务端使用";
        }
    }
    else if(m_policy == CallOnBroadcast)
    {
        if(role() == Host)
        {
            if(data->host->policy() == ROHost::Server)//本机以纯服务端的形式启动的，没有本地player
            {
                invokeMethod(this,funName,params);
                data->host->broadcastRPC(data->id,funName,params,data->host->players(),m_mode == Safe);
            }
            else{
                data->host->broadcastRPC(data->id,funName,params,data->host->players(),m_mode == Safe);
            }
        }
        else if(role() == Individual)
        {
            invokeMethod(this,funName,params);
        }
        else{
            qDebug()<<"RPC调用失败,CallOnBroadcast选项仅能在服务端使用";
        }
    }
}

RORPC::Policy RORPC::policy() const
{
    return m_policy;
}

void RORPC::setPolicy(Policy newPolicy)
{
    if (m_policy == newPolicy)
        return;
    m_policy = newPolicy;
    emit policyChanged();
}

RORPC::CallingMode RORPC::mode() const
{
    return m_mode;
}

void RORPC::setMode(const CallingMode &newMode)
{
    if (m_mode == newMode)
        return;
    m_mode = newMode;
    emit modeChanged();
}
